package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"goods/models"
	"math"
)

type GoodsController struct {
	beego.Controller
}

type Json struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *GoodsController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	author := c.GetString("author")

	goods := models.Goods{
		Name:   name,
		Price:  price,
		Author: author,
	}

	err := models.DB.Create(&goods).Error
	if err != nil {
		res := Json{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Json{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *GoodsController) List() {
	page, _ := c.GetInt("page")
	size := 5
	var count int64
	models.DB.Model(models.Goods{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size

	var allstu []models.Goods
	err := models.DB.Offset(offset).Limit(size).Find(&allstu).Error
	if err != nil {
		res := Json{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Json{
			Code: 200,
			Msg:  "展示成功",
			Data: allstu,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
